#!/bin/bash

# P2P Boot Tool (PBT), by Gabriel Winckler (C) 2009

#	This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

# This software has the influence of Clusters for Everyone, by Cicuttin Matteo,
#	a evolution of Hopeless by Christian Pellegrin

# Usage: [BASENAME] [INPUT DIR] [OUTPUT DIR]

# INPUT DIR: The directory with the root filesystem for the nodes
# OUTPUT DIR: The directory were the files will be created, as follow:
#   - BASENAME.metalink
#   - BASENAME-YYYYMMDD??.squashfs
#   - BASENAME-YYYYMMDD??.squashfs.torrent
#
#  ?? is the smallest number that don't overwrite any .squashfs file

SERVER=192.168.0.1
SERVER_URL=http://$SERVER
TRACKER_URL=http://$SERVER:6969/announce

do_serial()
{

	DATE=$(date +%Y%m%d)
	I="00"
	while [ 1 ]
	do
		if [ ! -f $DIR/$BASENAME-$DATE$I.squashfs ]
		then
			export SERIAL=$DATE$I
			return 0
		else
			I=$(printf '%02d' $((++I)))
		fi
	done
}

do_squashfs()
{
	mksquashfs $INPUT $DIR/$BASENAME-$SERIAL.squashfs
}

do_torrent()
{
	btmakemetafile $DIR/$BASENAME-$SERIAL.squashfs $TRACKER_URL
}

do_metalink()
{
	FILENAME=$BASENAME-$SERIAL.squashfs
	MD5=$(md5sum $DIR/$FILENAME | cut -d ' ' -f1)
	SHA1=$(sha1sum $DIR/$FILENAME | cut -d ' ' -f1)

	printf '<?xml version="1.0" encoding="UTF-8"?>
<metalink version="3.0" xmlns="http://www.metalinker.org">
  <files>
    <file name="%s">
      <verification>
        <hash type="md5">%s</hash>
        <hash type="sha1">%s</hash>
      </verification>
      <resources>
        <url type="http" preference="90">%s</url> 
        <url type="bittorrent" preference="100">%s</url>
      </resources>
    </file>
  </files>
</metalink>
' $FILENAME $MD5 $SHA1 $SERVER_URL/$FILENAME $SERVER_URL/$FILENAME.torrent > $DIR/$BASENAME.metalink

}

BASENAME=$1
INPUT=$2
DIR=$3

do_serial
echo $SERIAL
do_squashfs
do_torrent
do_metalink

echo
echo "Done!"
